package org.zoomdev.zoom.dao.executor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zoomdev.zoom.dao.DaoException;
import org.zoomdev.zoom.dao.SqlConfig;
import org.zoomdev.zoom.dao.configs.Delete;
import org.zoomdev.zoom.dao.configs.Where;
import org.zoomdev.zoom.dao.entity.Entity;
import org.zoomdev.zoom.dao.modules.CoreDaoModule;
import org.zoomdev.zoom.dao.utils.LogUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public final class DeleteExecutor implements SqlExecutor {

    private static final Logger log = LoggerFactory.getLogger(CoreDaoModule.NAME);

    public int execute(SqlConfig cfg, Object data) {
        if (data == null) {
            throw new NullPointerException();
        }
        Delete delete = cfg.getDelete();
        Where where = cfg.getWhere();
        Entity entity = cfg.getEntity();
        delete.prepare(cfg, entity, data);
        String sql = delete.buildSql(cfg, where);
        if (CoreDaoModule.logSql) {
            log.info(LogUtils.getSql(sql, where.getValues()));
        }
        try {
            Connection conn = cfg.openConnection();
            try (PreparedStatement stmt = conn.prepareStatement(sql)) {
                where.setParameter(stmt, 1);
                return stmt.executeUpdate();
            }
        } catch (SQLException e) {
            throw new DaoException("执行delete失败:" + LogUtils.getSql(sql, where.getValues()), e);
        }

    }


}
